//
//@File    :	8.8_filefunc.cpp
//@Time    :	2021/08/16 22:03:22
//@Auther  :	Sun Sheng
//@Contact :	970340843@qq.com
//@Desc    :	function with ostream &parameter
//

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

void file_it(ostream &os, double fo, const double fe[], int n);
const int LIMIT = 5;
int main()
{
    ofstream fout;
    const char *fn = "ep-data.txt";
    fout.open(fn);
    if (!fout.is_open())
    {
        cout << "Can't open " << fn << ". Bye.\n";
        exit(EXIT_FAILURE);
    }
    double objective;
    cout << "Enter the focal lenth of your "
         << "telescope objective in mm: ";
    cin >> objective;
    double eps[LIMIT];
    cout << "Enter the focal lenths,in mm,of " << LIMIT
         << " eyepieces:\n";
    for (int i = 0; i < LIMIT; i++)
    {
        cout << "Eyepiece #" << i + 1 << ": ";
        cin >> eps[i];
    }
    file_it(fout, objective, eps, LIMIT);
    //将目镜数据写入文件ep-data.txt中
    file_it(fout, objective, eps, LIMIT);
    //将同样的信息以同样的格式显示到屏幕上
    cout << "Done.\n";
    system("pause");
    return 0;
}
void file_it(ostream &os, double fo, const double fe[], int n)
{
    ios_base::fmtflags initial;
    //ios_base::fmtflags是储存格式化信息所需的数据类型名称
    //initial储存了file_it()之前的格式化设置
    initial = os.setf(ios_base::fixed);//将对象置于使用定点表示法的模式
    os.precision(0);
    os << "Focal length of objective: " << fo << " mm\n";
    os.setf(ios::showpoint);//将对象置于显示小数的模式
    os.precision(1);//指定显示多少位小数
    os.width(12);//设置下一次输出操作使用的字符宽度,只生效一次
    os << "f.1. eyepiece";
    os.width(15);
    os << "magnification" << endl;
    for (int i = 0; i < n; i++)
    {
        os.width(12);
        os << fe[i];
        os.width(15);
        os << int(fo / fe[i] + 0.5) << endl;
    }
    os.setf(initial);
    //setf()返回调用它之前有效的所有格式化设置
    //该函数将对象回到传递给file_it()之前的状态
}